package com.rihel.servlets.User;

import com.rihel.dao.UserDAO;
import com.rihel.model.User;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String uname = null;
        String pwd = null;
        User dbUser = null;
        User user = null;
        String[] isRem = null;

        if (hasParamInReq(request, "uname")) {
            uname = request.getParameter("uname");
            dbUser = userDAO.getUserByUname(uname);
        }
        if (hasParamInReq(request, "pwd")) {
            pwd = request.getParameter("pwd");
            System.out.println(pwd);
            if (dbUser.getPwd().equals(pwd)) {
                user = dbUser;



                if (hasParamsInReq(request, "isRem")) {
                    Cookie unameCookie = new Cookie("uname", uname);
                    unameCookie.setMaxAge(60 * 60 * 24 * 10);
                    response.addCookie(unameCookie);
                } else {
                    Cookie[] cookies = request.getCookies();
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("uname")) {
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                    }
                }
                request.getSession().setAttribute("user", user);
                response.sendRedirect("result.jsp?code=1");

            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private boolean hasParamInReq(HttpServletRequest req, String name) {
        return req.getParameter(name) != null;
    }

    private boolean hasParamsInReq(HttpServletRequest req, String name) {
        return req.getParameterValues(name) != null && req.getParameterValues(name).length > 0;
    }
}
